package com.example.crud.data.service.impl;

import com.example.crud.data.Executor;
import com.example.crud.data.entity.Student;
import com.example.crud.data.repository.StudentRepository;
import com.example.crud.data.service.StudentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;

@Service
@RequiredArgsConstructor
public class StudentServiceImpl implements StudentService {

    private final StudentRepository repository;

    @Override
    public Optional<Student> get(String id) {
        return repository.findById(id);
    }

    @Override
    public Optional<Student> remove(String id) {
        return repository.removeById(id);
    }

    @Override
    public String save(Student student) {
        if (!StringUtils.hasText(student.getId())) {
            student.setId(UUID.randomUUID().toString());
            repository.save(student);
        } else {
            repository.update(student);
        }
        return student.getId();
    }

    @Override
    public void saveIfAbsent(Student student, Executor executor) {
        if (StringUtils.hasText(student.getId()) && !repository.exists(student.getId())) {
            return;
        }

        if (!StringUtils.hasText(student.getId())) {
            student.setId(UUID.randomUUID().toString());
        }
        executor.execute();
        repository.save(student);
    }

    @Override
    public void saveIfPresent(String id, Consumer<Student> consumer) {
        Student student = repository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("not found"));

        consumer.accept(student);

        repository.update(student);
    }
}
